<template>
  <div>
    <Modal
      :loading="modelOkLoad"
      :styles="{ top: '60px' }"
      :title="title"
      :value="value"
      @on-cancel="handleCancelClick"
      @on-ok="handleOkClick"
      @on-visible-change="handleVisibleChange"
      width="600"
    >
      <Form :label-width="80" :model="form" :rules="formRules" ref="staffForm">
        <div class="form-item-wrapper">
          <FormItem label="姓名" prop="name">
            <Input
              :disabled="modelType === 'look'"
              @on-focus="handleResetModelLoading"
              placeholder="请输入名称"
              v-model="form.name"
            />
          </FormItem>
          <FormItem label="账号" prop="account">
            <Input
              :disabled="modelType === 'look'"
              @on-focus="handleResetModelLoading"
              placeholder="请输入账号"
              v-model="form.account"
            />
          </FormItem>
        </div>
        <div class="form-item-wrapper">
          <FormItem label="角色" prop="roleId">
            <Select
              :disabled="modelType == 'look'"
              @on-change="handleResetModelLoading"
              placeholder="请选择角色"
              v-model="form.roleId"
            >
              <Option
                :key="item.id"
                :value="item.id"
                v-for="item in roleList"
                >{{ item.name }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="岗位" prop="jobId">
            <Select
              :disabled="modelType == 'look'"
              @on-change="handleResetModelLoading"
              placeholder="请选择岗位"
              v-model="form.jobId"
            >
              <Option :key="item.id" :value="item.id" v-for="item in jobList">{{
                item.name
              }}</Option>
            </Select>
          </FormItem>
        </div>
        <div class="form-item-wrapper">
          <FormItem label="密码" prop="password">
            <Button
              :disabled="modelType == 'look' || modelType === 'add'"
              :loading="resetButtonLoading"
              @click="handleResetPasswordClick"
              type="primary"
              >重置密码</Button
            >
          </FormItem>
          <FormItem label="电子签名" prop="signature">
            <div class="upload-list" v-if="form.signature">
              <template>
                <img :src="`${form.signature}`" />
                <div class="upload-list-cover">
                  <Icon
                    @click.native="handleImgPreview"
                    type="ios-eye-outline"
                  ></Icon>
                  <!-- <Icon
                    @click.native="handleRemoveImg"
                    type="ios-trash-outline"
                    v-if="modelType !== 'look'"
                  ></Icon> -->
                </div>
              </template>
            </div>
            <!-- <Upload
              :action="fileUploadUrl"
              :on-remove="handleFileRemove"
              :on-success="handleFileUpload"
              :show-upload-list="false"
              :headers="uploadHeader"
              name="sign"
              ref="upload"
            >
              <Button
                :disabled="!!form.signature"
                icon="ios-cloud-upload-outline"
                type="primary"
                >上传图片</Button
              >
            </Upload> -->
          </FormItem>
        </div>
        <!-- <h3>项目部门及是否为管理者</h3> -->

        <div class="form-item-wrapper">
          <FormItem label="项目部门" prop="deparmentId">
            <Input
              disabled
              placeholder="请输入部门"
              v-model="form.departmentName"
            />
          </FormItem>
          <FormItem label="启用状态" prop="frozen" v-if="modelType !== 'add'">
            <i-switch
              :disabled="modelType === 'look'"
              :false-value="1"
              :loading="swicthLoading"
              :true-value="0"
              @on-change="handleSwitchChange"
              size="large"
              v-model="form.frozen"
            >
              <span slot="open">启用</span>
              <span slot="close">禁用</span>
            </i-switch>
          </FormItem>
        </div>
      </Form>
      <Spin fix size="large" v-if="modalLoading"></Spin>
    </Modal>

    <Modal title="查看电子签名" v-model="imgViewVisible">
      <img
        :src="`${imgName}`"
        style="width: 100%"
        v-if="imgViewVisible"
      />
    </Modal>
  </div>
</template>

<script>

import {
  staffAdd,
  getJobRoleList,
  getUserInfo,
  editStaffInfo,
  resetPassword,
  frozenAccount
} from '@/api/staff.js';
import config from '@/config';
// import { getHTTP, getToken } from '@/libs/util';

export default {
  model: {
    prop: 'value',
    event: 'on-visible-change'
  },
  props: {
    value: Boolean,
    isEdit: Boolean,
    oprStaffId: String | Number,
    selectTreeNode: Object,
    title: String
  },
  data () {
    return {
      userId: '', // 编辑时候
      form: {
        name: '', // 姓名
        account: '', // 账号
        deparmentId: '', // 部门编号
        roleId: '', // 角色
        jobId: '', // 岗位
        signature: '', // 签名图片地址
        departmentName: '',
        frozen: 0 // 启用状态
      },
      frozenCopy: 0,
      formRules: {
        name: [{ required: true, message: '请输入名称' }],
        account: [{ required: true, message: '请输入账号' }],
        roleId: [{ required: true, message: '请选择角色' }],
        jobId: [{ required: true, message: '请选择岗位' }],
        // signature: [{ required: true, message: '请上传电子签名' }],
        deparmentId: [{ required: true, message: '请输入部门' }]
      },
      // fileUploadUrl: getHTTP() + `${config.baseUrl.pro}/fileupload/uploadsign`,
      roleList: [],
      jobList: [],

      // 图片上传
      imgName: '',
      imgViewVisible: false,
      // uploadHeader: {
      //   Authorization: getToken()
      // },

      swicthLoading: false,
      modalLoading: true, // 模态框数据加载
      resetButtonLoading: false,
      modelType: 'add',
      modelOkLoad: true, // 点击确定以后

      config
    };
  },
  watch: {
    value: {
      handler: function (val) {
        if (val) {
          if (this.isEdit && this.oprStaffId) {
            this.getUserInfo();
          } else {
            // 不是编辑
            this.modalLoading = false;
            console.log(this.selectTreeNode, '编辑员工');
            this.form.deparmentId = this.selectTreeNode.nodeId;
            this.form.departmentName = this.selectTreeNode.nodeName;
          }
        }
      },
      immediate: true
    },
    title: function (val) {
      if (this.title === '查看员工') {
        this.modelType = 'look';
      } else if (this.title === '编辑员工') {
        this.modelType = 'edit';
      } else {
        this.modelType = 'add';
      }
    }
  },
  mounted () {
    this.getJobRoleList();
  },
  methods: {
    async getUserInfo () {
      // 查询用户信息
      const resp = await getUserInfo({ userId: this.oprStaffId });
      this.modalLoading = false;
      console.log(resp.data.data, 'resp.data.data');
      const {
        id,
        fullname,
        username,
        roleid,
        frozen,
        jobid,
        departmentname,
        deptid,
        signature
      } = resp.data.data;

      this.userId = id;
      this.form.name = fullname;
      this.form.account = username;
      this.form.roleId = roleid;
      this.form.frozen = frozen;
      this.form.jobId = jobid;
      this.form.departmentName = departmentname;
      this.form.deparmentId = deptid;
      this.form.signature = signature;
      this.frozenCopy = frozen;
      if (this.title === '查看员工') {
        this.modelType = 'look';
      } else if (this.title === '编辑员工') {
        this.modelType = 'edit';
      } else {
        this.modelType = 'add';
      }
    },
    async getJobRoleList () {
      const resp = await getJobRoleList({});
      const info = resp.data.data;
      this.roleList = info.roleList;
      this.jobList = info.jobList;
    },
    handleVisibleChange (visible) {
      this.$emit('on-visible-change', visible);
    },
    // handleFileUpload (response) {
    //   console.log(response, 'response');
    //   this.form.signature = response.data;
    //   this.handleResetModelLoading();
    // },
    // handleFileRemove () {
    //   this.form.signature = '';
    // },
    handleOkClick () {
      this.$refs.staffForm.validate(async valid => {
        const { name, account, deparmentId, roleId, jobId, signature } = this.form;
        if (valid) {
          const data = {
            name,
            account,
            deparmentId,
            roleId,
            jobId,
            signature
          };
          try {
            if (this.isEdit) {
              data.userId = this.userId;
              await editStaffInfo(data);
              // console.log('编辑保存 staff resp=>', resp);
            } else {
              // 添加员工
              // console.log('保存 staff data=>', data);
              await staffAdd(data);
            }
            this.$Message.success('保存成功');
            this.$emit('on-visible-change', false);
            this.$emit('on-save-success');
            // 确定修改，则将启用状态改为和表格内的启用状态一致
            this.frozenCopy = this.form.frozen;
            this.handleCancelClick();
          } catch (error) {
            console.error(error);
          }
        }
      });
    },
    handleResetModelLoading () {
      this.modelOkLoad = false;
      this.$nextTick(() => {
        this.modelOkLoad = true;
      });
    },
    async handleCancelClick () {
      this.$refs.staffForm.resetFields();
      this.modalLoading = true;
      this.resetButtonLoading = false;
      this.swicthLoading = false;
      // 如果取消前修改了启用状态，则将启用状态复原
      if (this.form.frozen !== this.frozenCopy) {
        const data = {
          ids: this.userId,
          frozen: this.frozenCopy
        };
        await frozenAccount(data);
      }
    },
    handleImgPreview () {
      this.imgName = this.form.signature;
      this.imgViewVisible = true;
    },
    handleRemoveImg () {
      this.form.signature = '';
    },
    async handleResetPasswordClick () {
      this.resetButtonLoading = true;
      await resetPassword({ userId: this.userId });
      this.resetButtonLoading = false;
      this.$Message.success('重置成功');
    },
    async handleSwitchChange (val) {
      this.swicthLoading = true;
      const data = {
        ids: this.userId,
        frozen: this.form.frozen ? 1 : 0
      };
      await frozenAccount(data);
      this.getFrozenStatus();
      this.swicthLoading = false;
    },
    async getFrozenStatus () {
      const resp = await getUserInfo({ userId: this.oprStaffId });
      this.$Message.success('修改成功');
      const info = resp.data.data;
      // this.frozenCopy = info.frozen;
      this.form.frozen = info.frozen;
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .ivu-modal-body {
  //   padding: 30px 90px 20px 30px;
  padding-right: 30px;
}
.page-wrapper {
  .ivu-page {
    float: right;
    margin: 10px 0;
  }
}
.form-item-wrapper {
  display: flex;
  > .ivu-form-item {
    width: 50%;
  }
}
.upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.upload-list img {
  width: 100%;
  height: 100%;
}
.upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.upload-list:hover .upload-list-cover {
  display: block;
}
.upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
